#------------------------------------------------------------------------------
# Import libraries
#------------------------------------------------------------------------------

rm(list=ls())
library(LalRUtils)
libreq(tidyverse, data.table, zoo, tictoc, 
       fst, fixest, PanelMatch, patchwork,
       rio, magrittr, janitor, did, panelView, 
       ggiplot, tictoc, binsreg, interflex)
set.seed(42)
theme_set(lal_plot_theme())

#------------------------------------------------------------------------------





#------------------------------------------------------------------------------
# Define Paths
#------------------------------------------------------------------------------

# R studio
setwd( dirname(rstudioapi::getActiveDocumentContext()$path) )
# R default : unccoment if you use default R
# setwd(getSrcDirectory(function(){})[1])

#------------------------------------------------------------------------------




#------------------------------------------------------------------------------
# Load Data
#------------------------------------------------------------------------------

vcf <- fread("vcf_data_complete.csv", sep = ",")
setnames( vcf, "d", "D")
vcf_data <- copy( vcf )
gfc <- fread("gfc_dta.csv" )


#------------------------------------------------------------------------------



#------------------------------------------------------------------------------
# Load Data
#------------------------------------------------------------------------------

# %% GFC estimate for PRI
gfc[, D_fra := sch * (year >= 2008)]

fitter = function(cutoff){
  dat = gfc[pref_bin >= cutoff & gfc3 == TRUE]
  m = feols(def_ha ~ D_fra | village[t] + styear, cluster = ~block, dat)
  return( m )
}

res <- list()
for ( i in 1:10 ){
  res[[i]] <-  fitter(i)
}


gfc[, ever_treated := max(D), .(village)]
fitter2 = function(cutoff){
  dat = gfc[pref_bin >= cutoff & gfc3 == TRUE]
  ctrl <- round(dat[ ever_treated == 0 & pesa_exposure == 0, mean(def_ha)], 2)
  treat <- round(dat[ ever_treated == 1 & pesa_exposure == 0, mean(def_ha)], 2)
  
}

ctrls <- c()
treats <- c()
for ( i in 1:10 ){
  dat = gfc[pref_bin >= i & gfc3 == TRUE]
  ctrl <- round(dat[ ever_treated == 0 & pesa_exposure == 0, mean(def_ha)], 2)
  treat <- round(dat[ ever_treated == 1 & pesa_exposure == 0, mean(def_ha)], 2)
  
  ctrls[i] <- ctrl
  treats[i] <- treat
}


# Change name of coefficients
treatmap =c(
  # GFC
  "def_ha"       = "Annual Deforestation in Hectares",
  "village"      = "Village",
  "village[t]"   = "Village + Village TT",
  # VCF
  "forest_index" = "Forest cover index",
  "green_index"  = "Non-Forest Vegetation",
  "built_index"  = "Bare Ground Indices",
  "cellid"       = "Pixel",
  "cellid[t]"    = "pixel + pixel TT",
  # both
  "yr"           = "Year",
  "year"         = "Year",
  "styear"       = "State $\\times$ Year",
  "D"            = "PESA $\\times$ Scheduled",
  "block"        = "Block",
  "blk"          = "Block", 
  "D_fra"        = "FRA $\\times$ Scheduled"   
)


fitstat_register("n_new", function(x) summary( x )$nobs , 
                 "\\# Observations")
desc = "Effects of Forest Rights act
(2008) on deforested area in GFC data"
fn = "figurea3_regs"; lab = "tab:figurea3_regs";
etable( res,
        style.tex = style.tex(main = "base", 
                              depvar.title = "", 
                              model.title = "", 
                              var.title = "\\midrule", 
                              slopes.title = "\\midrule \\emph{Time Trends}", 
                              yesNo = c("$\\checkmark$", ""), 
                              signif.code = NA, 
                              tablefoot = FALSE, 
                              line.bottom = "\\midrule \\midrule"),
        signif.code = NA,
        fixef_sizes = T, 
        fixef_sizes.simplify = F,
        fitstat = c( "n_new", "r2" ),
        notes = "\\emph{Notes:} Standard errors are clustered at the block level and reported in parentheses.",
        headers = c( "Cut Off = 1", "Cut Off = 2", "Cut Off = 3", "Cut Off = 4", 
                     "Cut Off = 5", "Cut Off = 6", "Cut Off = 7", "Cut Off = 8", 
                     "Cut Off = 9", "Cut Off = 10"),
        tex = TRUE,
        dict = treatmap,
        label = lab,
        title = glue::glue("{desc}"),
        extralines=list(
          "\\midrule \\emph{Summary Statistics}" = c( rep( " ", 10 ) ),
          "Mean Pre-Y (Non-Sch)"= ctrls,
          "Mean Pre-Y (Sch )"   = treats,
          "Dataset"     = c( rep( "GFC", 10 ) ),
          "Timespan"    = c( rep( "2001-2017", 10 ) )
        ),
        file = "appendix_figureA3_table.tex", 
        replace = TRUE
)





